﻿using Microsoft.Win32;
using Newtonsoft.Json;
using NPOI.SS.UserModel;
using NPOI.XSSF.UserModel;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Data;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using 基于WPF的电缆采样数据分析系统.Converters;
using 基于WPF的电缆采样数据分析系统.Models.Enums;
using 基于WPF的电缆采样数据分析系统.Models.ExportFormat;
using 基于WPF的电缆采样数据分析系统.Models.Task;
using 基于WPF的电缆采样数据分析系统.MsgEvents.AccountingReport;
using 基于WPF的电缆采样数据分析系统.Tools.LangugeTool;
using 基于WPF的电缆采样数据分析系统.Tools.LogTools;
using 基于WPF的电缆采样数据分析系统.Tools.MessagePopupTool;

namespace 基于WPF的电缆采样数据分析系统.Tools.TaskListTools
{
    public class ExportTaskList
    {
        public static ChannelConverter channelConverter = new ChannelConverter();

        /// <summary>
        /// 导出任务集合
        /// </summary>
        /// <param name="CurrentTaskList"></param>
        /// <returns></returns>
        public static RetResult ByFilePathExportTaskList(ObservableCollection<TaskDataInfo> CurrentTaskList)
        {
            try
            {
                SaveFileDialog saveFileDialog = new SaveFileDialog();

                // 设置标题
                saveFileDialog.Title = LangugeConvertor.GetValue("ExportTaskSet");

                // 设置过滤器
                saveFileDialog.Filter = $"XLSX {LangugeConvertor.GetValue("File")} (*.xlsx)|*.xlsx";

                // 设置默认扩展名
                saveFileDialog.DefaultExt = "xlsx";

                // 设置默认文件名
                saveFileDialog.FileName = LangugeConvertor.GetValue("ExportTaskSet") + DateTime.Now.ToString("yyyyMMddHHmmss");

                if (saveFileDialog.ShowDialog() == true)
                {
                    string selectedFilePath = saveFileDialog.FileName;

                    ObservableCollection<TaskDataInfoFormat> taskDataInfoFormats = TaskDataInfoToTaskDataInfoFormat(CurrentTaskList);

                    WriteExcel(taskDataInfoFormats, selectedFilePath);

                    // 赋值日志文件的文件名
                    string[] newStr = selectedFilePath.Split("\\");

                    // 添加使用过文件的日志到集合中
                    FileTypeLog.AddUsedFileLogToList(FileType.ExportTaskListFile, newStr[newStr.Length - 1], LangugeConvertor.GetValue("ExportTaskCollectionFile"), GlobalVariableEdit.CurrentUserInfo.Uid);

                    // 更新操作日志
                    GlobalLogTool.Instance.AddLogToTDRWork(GlobalVariableEdit.CurrentUserInfo.Uid, LangugeConvertor.GetValue("ExportTaskCollectionFile") + ": 【" + newStr[newStr.Length - 1] + "】");

                    return RetResult.Success;
                }

                return RetResult.Fail;

            }
            catch (Exception e)
			{
                MessagePopup.DisplayMessagePopup(LangugeConvertor.GetValue("CauseOfError") + e.Message);
                return RetResult.Fail;
            }
        }


        private static ObservableCollection<TaskDataInfoFormat> TaskDataInfoToTaskDataInfoFormat(ObservableCollection<TaskDataInfo> CurrentTaskList)
        {
            ObservableCollection<TaskDataInfoFormat> taskDataInfoFormats = new ObservableCollection<TaskDataInfoFormat>();

            for (int i = 0; i < CurrentTaskList.Count; i++)
            {
                taskDataInfoFormats.Add(new TaskDataInfoFormat()
                {
                    Tid = CurrentTaskList[i].Tid,
                    DescriptionInfo = CurrentTaskList[i].DescriptionInfo,
                    ChannelConfig = (string)channelConverter.Convert(CurrentTaskList[i].ChannelConfig, typeof(string), null, null),
                    XAxisOrigin = CurrentTaskList[i].HorizontalArgument.AxisOrigin,
                    XAxisEndPoint = CurrentTaskList[i].HorizontalArgument.AxisEndPoint,
                    XAxisScale = CurrentTaskList[i].HorizontalArgument.AxisScale,
                    YAxisOrigin = CurrentTaskList[i].VerticalArgument.AxisOrigin,
                    YAxisEndPoint = CurrentTaskList[i].VerticalArgument.AxisEndPoint,
                    YAxisScale = CurrentTaskList[i].VerticalArgument.AxisScale,
                    CreateUser = CurrentTaskList[i].CreateUser,
                    UpdateUser = CurrentTaskList[i].UpdateUser,
                    CreateTime = CurrentTaskList[i].CreateTime,
                    UpdateTime = CurrentTaskList[i].UpdateTime,
                    XAxisTranslation = CurrentTaskList[i].XAxisTranslation,
                    YAxisTranslation = CurrentTaskList[i].YAxisTranslation,
                });
            }

            return taskDataInfoFormats;
        }

        /// <summary>
        /// 写Excel文件
        /// </summary>
        /// <param name="CurrentTaskList"></param>
        /// <param name="SelectedFilePath"></param>
        private static void WriteExcel(ObservableCollection<TaskDataInfoFormat> CurrentTaskList, string SelectedFilePath)
        {

            // Lets converts our object data to Datatable for a simplified logic.
            // Datatable is most easy way to deal with complex datatypes for easy reading and formatting.

            DataTable table = (DataTable)JsonConvert.DeserializeObject(JsonConvert.SerializeObject(CurrentTaskList), (typeof(DataTable)));
            var memoryStream = new MemoryStream();

            using (var fs = new FileStream(SelectedFilePath, FileMode.Create, FileAccess.Write))
            {
                IWorkbook workbook = new XSSFWorkbook();
                ISheet excelSheet = workbook.CreateSheet("Sheet1");

                List<String> columns = new List<string>();
                IRow row = excelSheet.CreateRow(0);
                int columnIndex = 0;

                foreach (System.Data.DataColumn column in table.Columns)
                {
                    columns.Add(column.ColumnName);
                    row.CreateCell(columnIndex).SetCellValue(column.ColumnName);
                    columnIndex++;
                }

                int rowIndex = 1;
                foreach (DataRow dsrow in table.Rows)
                {
                    row = excelSheet.CreateRow(rowIndex);
                    int cellIndex = 0;
                    foreach (String col in columns)
                    {
                        row.CreateCell(cellIndex).SetCellValue(dsrow[col].ToString());
                        cellIndex++;
                    }

                    rowIndex++;
                }
                workbook.Write(fs);
            }

        }
    }
}
